import { HTTP } from '../utils/http.js'

class Classic extends HTTP {
  getLatest(callBack) {
    this.request({
      url: 'classic/latest',
      success: res => {
        callBack(res)
        this._setLatestIndex(res.index)
        wx.setStorageSync(this._getKey(res.index), res)
      }
    })
  }
  getClassic(index, nextOrPrevious, callBack) {
    const key =
      nextOrPrevious === 'next'
        ? this._getKey(index + 1)
        : this._getKey(index - 1)
    const classic = wx.getStorageSync(key)
    if (!classic) {
      this.request({
        url: `classic/${index}/${nextOrPrevious}`,
        success: res => {
          wx.setStorageSync(this._getKey(res.index), res)
          callBack(res)
        }
      })
    } else {
      callBack(classic)
    }
  }

  isFirst(index) {
    return index === 1 ? true : false
  }

  isLatest(index) {
    const latestIndex = this._getLatestIndex()
    return index === latestIndex ? true : false
  }

  _setLatestIndex(index) {
    wx.setStorageSync('latest', index)
  }

  _getLatestIndex() {
    return wx.getStorageSync('latest')
  }

  _getKey(index) {
    return `classic-${index}`
  }
}

export { Classic }
